import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.simple.SimpleFeature;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class connPostGIS {
    /**
     * 连接PostGIS数据库;
     * 读取一个gis数据表，并返回第一个要素的某个字段值
     * @return
     * @throws IOException
     */
    public static String connDBTest() throws IOException {
        String result="";
        Map<String, Object> lpParmsConn = new HashMap<String, Object>();
        //数据库连接参数
        lpParmsConn.put(PostgisNGDataStoreFactory.DBTYPE.key, "postgis");
        lpParmsConn.put(PostgisNGDataStoreFactory.HOST.key, "192.168.108.50");
        lpParmsConn.put(PostgisNGDataStoreFactory.PORT.key, 5432);
        //数据库名称
        lpParmsConn.put(PostgisNGDataStoreFactory.DATABASE.key, "gisdb");
        //用户名和密码
        lpParmsConn.put(PostgisNGDataStoreFactory.USER.key, "postgres");
        lpParmsConn.put(PostgisNGDataStoreFactory.PASSWD.key, "gisAdmin.1");
        DataStore pgDataStore = DataStoreFinder.getDataStore(lpParmsConn);
        System.out.println("getClass结果："+pgDataStore.getClass().getTypeName());
        System.out.println(pgDataStore.getClass().getName());
        System.out.println(pgDataStore.getClass().getSimpleName());
        System.out.println("=====");
        SimpleFeatureSource lpFea=pgDataStore.getFeatureSource("cities");
        SimpleFeatureCollection lpColl=lpFea.getFeatures();
        FeatureIterator<SimpleFeature> lpItertor=lpColl.features();
        while (lpItertor.hasNext()){
            SimpleFeature tFea=lpItertor.next();
            result= tFea.getAttribute("city_name").toString();
            break;
        }
        lpItertor.close();
        //最后释放数据库连接
        pgDataStore.dispose();
        return result;
    }

    /**
     * 返回PostGIS库的DataStore实例
     * 注：在外部使用后需要及时的释放连接
     * @return
     * @throws IOException
     */
    public static DataStore connPg() throws IOException{
        Map<String, Object> lpParmsConn = new HashMap<String, Object>();
        //数据库连接参数
        lpParmsConn.put(PostgisNGDataStoreFactory.DBTYPE.key, "postgis");
        lpParmsConn.put(PostgisNGDataStoreFactory.HOST.key, "192.168.108.50");
        lpParmsConn.put(PostgisNGDataStoreFactory.PORT.key, 5432);
        //数据库名称
        lpParmsConn.put(PostgisNGDataStoreFactory.DATABASE.key, "gisdb");
        //用户名和密码
        lpParmsConn.put(PostgisNGDataStoreFactory.USER.key, "postgres");
        lpParmsConn.put(PostgisNGDataStoreFactory.PASSWD.key, "gisAdmin.1");
        return DataStoreFinder.getDataStore(lpParmsConn);
    }
}
